<template>
  <div class="search-container" :class="{list:isResultShow}">
    <!-- 搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <form action="/" class="search-form">
      <van-search
        v-model="query.keyword"
        show-action
        placeholder="请输入搜索关键词"
        background="#1989fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索历史记录 -->
    <template v-if="!isResultShow">
      <van-cell title="历史记录">
        <div v-if="isDelete">
          <span @click="searchHistories=[]">全部删除</span>&nbsp;&nbsp;
          <span @click="isDelete=false">完成</span>
        </div>
        <van-icon v-else @click="isDelete=true" name="delete"></van-icon>
      </van-cell>
      <van-cell v-if="searchHistories.length">
        <van-tag plain type="primary" @click.native="clickHandler(index)" @close="clickHandler(index)"  v-for="(item,index) in searchHistories" :key="item"  size="large" :closeable="isDelete">{{item}}</van-tag>
      </van-cell>
      <van-cell v-else>
         <van-empty description="暂无历史记录" />
      </van-cell>
    </template>
    <!-- /搜索历史记录 -->

    <!-- 搜索结果 -->
    <template v-else>
       <!-- 筛选区域 -->
      <van-dropdown-menu v-if="goodList.length" class="fixed-filter">
        <van-dropdown-item v-model="query.sort" :options="option" @change="filterGetList" />
      </van-dropdown-menu>

      <!-- 列表内容 -->
      <van-empty v-if="goodList.length===0 && !error && !loading" description="暂无商品数据信息" />
      <van-list :immediate-check="false" v-model="loading"  @load="initData" :finished-text="goodList.length===0 ?'':'我也是有底线的'" :finished="finished" :error.sync="error">
        <GoodList :list="goodList" />
      </van-list>
    </template>
    <!-- /搜索结果 -->
  </div>
</template>

<script>
import { setItem, getItem } from "@/utils/storage";
import GoodList from '@/components/good-list'
import { getProductSearch } from "@/api/goods";
export default {
  name: "good",
  components: {
    GoodList,
  },
  data() {
    return {
      query:{
        keyword:'',  // 关键字
        pageNum:1,   // 页码
        pageSize:10, // 每页数量
        sort:0   // 排序字段:0->按相关度；1->按新品；2->按销量；3->价格从低到高；4->价格从高到低,可用值:0,1,2,3,4
      },
      goodList: [],
      loading:false,
      finished:false,
      error:false,
      total:'', // 总数
      option: [
        { text: '默认排序', value: 0 },
        { text: '新款商品', value: 1 },
        { text: '热销商品', value: 2 },
        { text: '价格升序', value: 3 },
        { text: '价格降序', value: 4 },
      ],
      isResultShow: false, // 搜索结果是否展示
      isDelete:false,
      searchHistories: getItem("serach-histories") || [],
    };
  },
  created() {
    Object.keys(this.$route.query).forEach(key=>{
      this.query[key] = this.$route.query[key]
    })
  },
   watch: {
    searchHistories(val) {
      if(val.length ===0 ) this.isDelete = false
      // 同步到本地存储
      setItem("serach-histories", val);
    },
  },
  methods: {
    // 获取列表数据
    async initData() {
      this.loading = true
      try {
        const { list,total } = await getProductSearch(this.query);
        this.goodList.push(...list)
        this.total = total
        if(this.goodList.length === total) this.finished = true
      } catch (error) {
        console.log(error);
      }
      this.loading = false
    },
    // 筛选重新拉取列表
    filterGetList(){
      this.goodList = []
      this.initData()
    },
     //   取消事件   【点击了取消按钮或者关闭图标】
    onCancel() {
      this.$router.back()
    },
    onSearch(val) {
      if(val.trim().length ===0 ) return false
      this.query.keyword = val
      this.isResultShow = true
      const set = new Set(this.searchHistories)
      set.delete(val)
      set.add(val)
      this.searchHistories = Array.from(set).reverse()
      this.goodList = []
      this.initData()
    },
    // 点击
    clickHandler(idx){
      if(this.isDelete){
        this.searchHistories.splice(idx,1)
      }else{
        this.onSearch(this.searchHistories[idx])
      }
    }
  },
};
</script>
<style lang="less" scoped>
.van-tag{
  margin-right: 20px;
  margin-bottom: 20px;
}
.search-container.list{
    padding-top: 190px;
}
.search-container {
  min-height: 100vh;
   padding-top: 120px;
  background-color: #fff;
  box-sizing: border-box;
 
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  .fixed-filter{
    position: fixed;
    top: 100px;
    z-index:1000;
    width: 100%;
  }
}
</style>